package com.hliushi.lock.web;

import com.hliushi.lock.service.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class StockController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisLock redisLock;

    @Resource
    private CuratorFramework curatorFramework;


    @Resource
    private RedissonClient redissonClient;

    /**
     * 不使用锁
     *
     * @return
     */
    @GetMapping("/stock1")
    public String stock1() {
        int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
        if (stock > 0) {
            stock--;
            stringRedisTemplate.opsForValue().set("stock", stock + "");
            System.out.println("库存扣减成功，剩余库存：" + stock);
        } else {
            System.out.println("库存不足！！！");
        }
        // 高并发下, 5个线程, 每秒4次请求, 重复30次 -> 出现超卖情况
        // 库存扣减成功，剩余库存：49
        // 库存扣减成功，剩余库存：48
        // 库存扣减成功，剩余库存：47
        // 库存扣减成功，剩余库存：47
        // 库存扣减成功，剩余库存：46
        // 库存扣减成功，剩余库存：46
        // 库存扣减成功，剩余库存：45
        // 库存扣减成功，剩余库存：45
        return "OK";
    }

    /**
     * 使用Java的锁机制
     *
     * @return
     */
    @GetMapping("/stock2")
    public String stock2() {
        synchronized (this) {
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                stock--;
                stringRedisTemplate.opsForValue().set("stock", stock + "");
                System.out.println("库存扣减成功，剩余库存：" + stock);
            } else {
                System.out.println("库存不足！！！");
            }
        }
        return "OK";
    }

    /**
     * 使用Redis分布式锁---无阻塞 --> 100个请求, 会有大部分请求拿不到锁直接返回了
     * 无堵塞 --> 适合秒杀活动, 大部分人是获得不到锁 --> 大部分人抢不到
     *
     * @return
     */
    @GetMapping("/stock3")
    public String stock3() {
        //尝试获取锁
        String mylock = redisLock.tryLock("MYLOCK", 2000);

        if (mylock != null) {
            //获取到了锁
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                stock--;
                stringRedisTemplate.opsForValue().set("stock", stock + "");
                System.out.println("库存扣减成功，剩余库存：" + stock);
            } else {
                System.out.println("库存不足！！！");
            }
            redisLock.unlock("MYLOCK", mylock);
        }

        return "OK";
    }

    /**
     * 使用Redis分布式锁---有阻塞
     *
     * @return
     */
    @GetMapping("/stock4")
    public String stock4() {
        // 尝试获取锁, 会在一秒之内不断的尝试获取锁
        String mylock = redisLock.lock("MYLOCK", 2000, 1000);

        if (mylock != null) {
            //获取到了锁
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                stock--;
                stringRedisTemplate.opsForValue().set("stock", stock + "");
                System.out.println("库存扣减成功，剩余库存：" + stock);
            } else {
                System.out.println("库存不足！！！");
            }
            redisLock.unlock("MYLOCK", mylock);
        }

        return "OK";
    }

    /**
     * 基于ZK实现分布式锁
     *
     * @return
     */
    @GetMapping("/stock6")
    public String stock6() {
        InterProcessMutex mutex = new InterProcessMutex(curatorFramework, "/mylock");

        try {
            // 尝试获取锁
            boolean locked = mutex.acquire(3, TimeUnit.SECONDS);
            if (locked) {
                // 获取到分布式锁
                int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
                if (stock > 0) {
                    stock--;
                    stringRedisTemplate.opsForValue().set("stock", stock + "");
                    System.out.println("库存扣减成功，剩余库存：" + stock);
                } else {
                    System.out.println("库存不足！！！");
                }
                // 释放锁
                mutex.release();
            } else {
                System.out.println("没有获取锁，不能执行减库存操作！！！");
            }
        } catch (Exception e) {
            log.error("争抢锁异常 error : {}", e.getMessage());
        }

        return "OK";
    }

    /**
     * 基于Redisson方式实现分布式锁
     *
     * @return
     */
    @GetMapping("/stock7")
    public String stock7() {
        // 获得锁对象
        RLock lock = redissonClient.getLock("mylock");

        try {
            // 尝试获取锁, 如果获取不到, 则阻塞, 如果加锁成功则后序程序继续运行 leaseTime为失效时间
            lock.lock(5000, TimeUnit.MILLISECONDS);
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                stock--;
                stringRedisTemplate.opsForValue().set("stock", stock + "");
                System.out.println("库存扣减成功，剩余库存：" + stock);
            } else {
                System.out.println("库存不足！！！");
            }
        } catch (NumberFormatException e) {
            log.error("争抢锁异常...");
        } finally {
            // 释放锁
            lock.unlock();
        }

        return "OK";
    }
}